package com.police.db;

/**
 * Created by LEO on 13-6-6.
 */

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class HistoryManager {
    private DBHelper helper;
    private SQLiteDatabase db;

    public HistoryManager(Context context) {
        helper = new DBHelper(context);
        //因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0, mFactory);
        //所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里
        db = helper.getWritableDatabase();
    }

    /**
     * add Historys
     *
     * @param Historys
     */
    public void add(List<History> Historys) {
        db.beginTransaction();    //开始事务
        try {
            for (History History : Historys) {
                db.execSQL("INSERT INTO History VALUES(null, ?, ?, ?,?,?,?)", new Object[]{History.userName, History.time, History.lac, History.cid, History.lat, History.lon});
            }
            db.setTransactionSuccessful();    //设置事务成功完成
        } finally {
            db.endTransaction();    //结束事务
        }
    }

    /**
     * del History
     *
     * @param userName
     */
    public void del(String userName) {
        db.delete("History", "userName = ?", new String[]{userName});
    }

    /**
     * query all Historys, return list
     *
     * @return List<History>
     */
    public List<History> query() {
        ArrayList<History> Historys = new ArrayList<History>();
        Cursor c = queryTheCursor();
        while (c.moveToNext()) {
            History History = new History();
            History._id = c.getInt(c.getColumnIndex("_id"));
            History.time = c.getString(c.getColumnIndex("time"));
            History.userName = c.getString(c.getColumnIndex("userName"));
            History.lac = c.getString(c.getColumnIndex("lac"));
            History.cid = c.getString(c.getColumnIndex("cid"));
            History.lon = c.getString(c.getColumnIndex("lon"));
            History.lat = c.getString(c.getColumnIndex("lat"));
            Historys.add(History);
        }
        c.close();
        return Historys;
    }

    /**
     * query all Historys, return cursor
     *
     * @return Cursor
     */
    public Cursor queryTheCursor() {
        Cursor c = db.rawQuery("SELECT * FROM History", null);
        return c;
    }

    /**
     * close database
     */
    public void closeDB() {
        db.close();
    }
}

